//--------------------------------------------------------------------------------------------------------------------
// register the functions
var newRegistery1 = new Array( "getContracts", "fillContractsPickList" );
var newRegistery2 = new Array( "getSelectedContractInfo", "displaySelectedContractInfo" );
allJsonsRegistry = allJsonsRegistry.concat(newRegistery1); 
allJsonsRegistry = allJsonsRegistry.concat(newRegistery2); 

//--------------------------------------------------------------------------------------------------------------------
// this function fills the pick list with the betroom
function fillContractsPickList( contractList )
{
    // create reference to first select
    sel1 = document.getElementById("id_contractDropList");

    //get the total item from the dropDownList   
    var intTotalItems = sel1.options.length;

    //loop through the number of items and remove them
    for(var intCounter=intTotalItems;intCounter>=0;intCounter--)
    {
        sel1.remove(intCounter);
    }

    // create the text which indicate what do the option
    sel1.options[sel1.length++] = new Option("Select a contract", "Select a contract");
   
    // fill the first dropdown uninvested stategies
     for (var i = 0; i < contractList.contracts.length; i++)
     {
        var contractName = contractList.contracts[i].name;
        sel1.options[sel1.length++] = new Option( contractName, contractName );
     }
};

//--------------------------------------------------------------------------------------------------------------------
// this notify the server that the user has last visited the specified contract so that it will send the correct information at the request
function requestSelectedContract()
{
    return submitWithoutReload( 
        '/requestSelectedContract/',
        $('#id_SelectContract'),
        '#id_messageDiv',
        ''
        );
};

//--------------------------------------------------------------------------------------------------------------------
//---- add my other people order info table
function addListOfOther( orderList, divParent, type )
{
    var divName = 'id_other'+type;
    var divTitle = "Liste des offres d'achat des autres joueurs";
    var divTableTitle = "Prix d'achat";
    var actionDiv = 'id_hitBid';
    var actionFuncName = 'hitBid()';
    var actionDivTitle = 'Vendre au plus offrant!';
    var alternativeMsg = 'D&eacute;sol&eacute;, vous &ecirc;tes le seul joueur &agrave acheter ce contrat.';
    var msgDiv = 'id_messageDivHitBid';
    if( type =='offer' )
    {
        divTitle = "Liste des offres de vente des autres joueurs";
        divTableTitle = "Prix de vente";
        actionDiv = 'id_liftOffer';
        actionFuncName = 'liftOffer()';
        actionDivTitle = 'id_liftOffer';
        actionDivTitle = 'Acheter au moins cher!';
        alternativeMsg = 'D&eacute;sol&eacute;, vous &ecirc;tes le seul joueur &agrave vendre ce contrat.'
        var msgDiv = 'id_messageDivLiftOffer';
    }
	$('#'+divParent).append('<div class="myHalfHeight myRoundCorners"  id="'+divName+'"/>');
	$('#'+divName).append('<div class="mySmallestStartOfLine" style="font-weight:bold;">'+divTitle+'&nbsp;&nbsp;</div>');
	if( orderList.length != 0 )
	{
	    $('#'+divName).append('<div  id="'+actionDiv+'"><input type="submit" class="myRoundCorners" onclick="'+actionFuncName+'" value="'+actionDivTitle+'" /></div>');
	    $('#'+divName).append('<div id="'+msgDiv+' style="color:red;"/>');
	    $('#'+divName).append('<table class="myTable" id="'+divName+'Table"></table>');
	    myTable = document.getElementById(divName+'Table');
	     // add the header
        var headerRow = myTable.insertRow(0);
        var newCell = headerRow.insertCell(0);
        newCell.innerHTML = '<th><div class="myBold">&nbsp;'+divTableTitle+'&nbsp;</div></th>';
        newCell = headerRow.insertCell(1);
        newCell.innerHTML = '<th><div class="myBold">&nbsp;Nombre disponible&nbsp;</div></th>';    
	    for( var i = 0; i <  orderList.length; ++ i )
	    {
	        var newRow = myTable.insertRow(i+1);
            var newCell = newRow.insertCell(0);
            newCell.innerHTML = orderList[i].price;
            newCell = newRow.insertCell(1);
            newCell.innerHTML = '<div name="'+divName+i+ '" >'+orderList[i].number+'</div>';
	    }
	}
	else
	{
	    $('#'+divName).append('<div class="oneLine">&nbsp;</div>');//finishes the line
	    $('#'+divName).append('<div class="oneLine" style="float:left; text-align:left">'+alternativeMsg+'</div>');
	}
}

//--------------------------------------------------------------------------------------------------------------------
//---- add my order info table
function addMyList( myList, parentDiv, typeStr, boundPrice )
{
    var id_str = 'id_my'+typeStr;
    $('#'+parentDiv).append('<div class="myHalfHeight myRoundCorners" id="'+id_str+'" " ></div>');
    
    var infTitle = "Mes offres d'achat";
    var infoMsg = '<div>Faire une nouvelle offre d\achat entre 1 and ' + boundPrice+' chochoros</div>';
    var onClickFuncName = 'addABid';
    var msgDiv = 'id_messageDivAddBid';
    var modifyNumberFuncName ='specifyNumberOfBids';
    if( typeStr =='offer' )
    {
        infTitle = "Mes offres de vente";
        infoMsg = '<div>Faire une nouvelle offre de vente entre ' +boundPrice+' et 99 chochoros</div>';
        onClickFuncName = 'addAnOffer';
        msgDiv = 'id_messageDivAddOffer';
        modifyNumberFuncName ='specifyNumberOfOffers';
    }
    $('#'+id_str).append('<div style="font-weight:bold;" >'+infTitle+'</div>');
    if( myList.length != 0 )
	{
	    $('#'+id_str).append('<table class="myTable" id="'+id_str+'Table"></table>');
	    myTable = document.getElementById(id_str+'Table');
	     // add the header
        var headerRow = myTable.insertRow(0);
        var newCell = headerRow.insertCell(0);
        newCell.innerHTML = '<th><div class="myBold">Prix</div></th>';
        newCell = headerRow.insertCell(1);
        newCell.innerHTML = '<th><div class="myBold">Nombre disponible</div></th>';    
	    for( var i = 0; i <  myList.length; ++ i )
	    {
	        var newRow = myTable.insertRow(i+1);
            var newCell = newRow.insertCell(0);
            newCell.innerHTML = myList[i].price;
            newCell = newRow.insertCell(1);
            newCell.innerHTML = '<div id="id_'+modifyNumberFuncName+i+'"/>';
            var tmp = '<input size="10" id="'+id_str+i+'"  name="specifiedNbOfContract" onkeypress="ifEnterArg(this,event,'+modifyNumberFuncName+',\''+i.toString()+'\');" value="'+myList[i].number+'"/>';
            $('#id_'+modifyNumberFuncName+i).append(tmp);
            tmp ='<input style="display:none;"  name="specifiedPrice" id="id_'+modifyNumberFuncName+i+'" value="'+myList[i].price+'"/>';
            $('#id_'+modifyNumberFuncName+i).append(tmp);
	    }
	}
	$('#'+id_str).append('<div id="'+id_str+'Suggest"/>');
	$('#'+id_str+'Suggest').append(infoMsg);
	$('#'+id_str+'Suggest').append('<input size="10" class="mySmallestStartOfLine" onkeypress="ifEnter(this,event,'+onClickFuncName+');"  name="newPrice"></input>');
	$('#'+id_str+'Suggest').append('<input type="submit" class="myRoundCorners" onclick="'+onClickFuncName+'()" value="Add another '+typeStr+'" />' );
	$('#'+id_str+'Suggest').append('<div id="'+msgDiv+'" style="color:red;"/>');
}

 

//--------------------------------------------------------------------------------------------------------------------
// Display the infrmation related to the seleced contract.
function displaySelectedContractInfo( contractInfo ) 
{
    $("#id_selectedContract").html("");
	var generalInfo = contractInfo.generalInfo[0];
	if( typeof(generalInfo.empty) != 'undefined' )
	{ 
	    return;
	}
	$("#id_selectedContract").addClass("section");
	$("#id_selectedContract").append('<h2>'+ generalInfo.name +'</h2>');
	
	//- FIRST BLOCK
	$("#id_selectedContract").append('<div class="oneLine2" id="id_contractDescription">' );
	$("#id_contractDescription").append('<div class="mySmallestStartOfLine" id="id_contractDexcitption" style="font-weight:bold;">Contrat description:&nbsp;</div> ' );
	$("#id_contractDescription").append('<div class="myThreeQuartersOfWidth">'+generalInfo.description+'</div>');
    
    var helpStr1 ='<a class="help" href="#" ><img border="0" src="'+STATIC_URL_JS+'images/help.png "><div class="helpText myRoundCorners">';
    var helpStr2 = '</div></a>';
  
    //-------------- Second BLOCK
    //------------- section for the transactions when they are allowed or warning when they are not 
    if( generalInfo.settlementStatus == - 2 )// dispplay the section for the transaction
    {
        $('#id_selectedContract').append('<BR>&nbsp;<BR>');
        $("#id_selectedContract").append('<div id="id_buyAndSellContractsCenter"></div>');
        $("#id_buyAndSellContractsCenter").append('<div id="id_buyAndSellContracts"></div>');
  	    $("#id_buyAndSellContracts").append('<div class="myHalfWidth" id="id_buyAContract"></div>');
  	    var helpStr = 'Pour acheter un contrat, vous pouvez accepter l\'offre de vente la plus basse (section \'Liste des offres de vente des autres joueurs\') ';
  	    helpStr += 'ou indiquer &agrave; quel prix vous souhaiteriez qu\'un autre joueur vous vende un contrat (section \'Mes offres d\'achat\').';
  	    var transactionTitleStart = '<div><div class="myHalfWidth" style="font-size:larger; font-weight:bold;">';
  	    $("#id_buyAContract").append(transactionTitleStart+'ACHETER UN CONTRAT </div>'+helpStr1+helpStr+helpStr2+'</div>');
  	    $('#id_buyAContract').append('<BR>&nbsp;<BR>');
        addListOfOther( 
            contractInfo.orderBookInfo[0].offerList,
            'id_buyAContract',
            'offer'
            );
            
        var minOfferMinus1 = 99;
        if( contractInfo.orderBookInfo[0].offerList.length > 0 )
        {
            // offers are  sorted in the increasing order
            minOfferMinus1  = Math.min( Math.max(contractInfo.orderBookInfo[0].offerList[0].price - 1, 0 ), minOfferMinus1 );
        }
        if( contractInfo.myOrders[0].offerList.length > 0 )
        {
            // offers are  sorted in the increasing order
            minOfferMinus1  = Math.min( Math.max(contractInfo.myOrders[0].offerList[0].price - 1, 0 ), minOfferMinus1 );
        }
        
        addMyList(
            contractInfo.myOrders[0].bidList,
            'id_buyAContract',
            'bid',
            minOfferMinus1
        );
            
        //---- other people offer info table and my offer info table (a half of the block)
        $("#id_buyAndSellContractsCenter").append('<div class="myHalfWidth" id="id_sellAContract"></div>');
        helpStr = 'Pour vendre un contrat, vous pouvez accepter l\'offre d\'achat la plus elev&eacute;e (section \'Liste des offres d\'achat des autres joueurs\') ';
  	    helpStr += 'ou indiquer &agrave; quel prix vous souhaiteriez qu\'un autre joueur vous ach&egrave;te un contrat (section \'Mes offres de vente\').';
  	    $("#id_sellAContract").append(transactionTitleStart+'VENDRE UN CONTRAT </div>' +helpStr1+helpStr+helpStr2+'</div>');
        $('#id_sellAContract').append('<BR>&nbsp;<BR>');
        addListOfOther( 
            contractInfo.orderBookInfo[0].bidList,
            'id_sellAContract',
            'bid'
            );
        var maxOfferPlus1 = 1;
        if( contractInfo.orderBookInfo[0].bidList.length > 0 )
        {
            maxOfferPlus1 = Math.max( Math.min(contractInfo.orderBookInfo[0].bidList[0].price + 1, 100 ), maxOfferPlus1 );
        }
        if( contractInfo.myOrders[0].bidList.length > 0 )
        {
            maxOfferPlus1 = Math.max( Math.min(contractInfo.myOrders[0].bidList[0].price + 1, 100 ), maxOfferPlus1 );
        }
        addMyList(
            contractInfo.myOrders[0].offerList,
            'id_sellAContract',
            'offer',
            maxOfferPlus1
        );
	}
	else {// generalInfo.settlementStatus > - 2 ) : display a warning indicating that the transaction are not authorised
        tmpStr = 'This Contract has fixed and is waiting for settlement. ';
        if( generalInfo.settlementStatus == 0 ) {
            vtmpStr = 'This Contract is already settled. Contract holders received nothing. ';
        }
        if( generalInfo.settlementStatus == 1 ) {
            tmpStr = 'This Contract is already settled. Contract holders received 100 chochoros per contract. ';
        }
        if( generalInfo.settlementStatus == 2 ) {
            tmpStr = 'This Contract is already settled. Unfortunatly, it was not possible to determine either it should pay or not. Buyers have been refunded. ';
        }
        $("#id_selectedContract").append( '<div class="myThreeQuartersOfWidth" style="color:red;">'+tmpStr+'It cannot be traded any longuer.</div>' );
    }
	
	//-------------- THIRD BLOCK
	//------------- info table (a third of the block)
	$("#id_selectedContract").append('<div class="oneLine2" id="id_infoAndGraphBlock"></div>');
	$('#id_infoAndGraphBlock').append('<BR>&nbsp;<BR>');
    $("#id_infoAndGraphBlock").append('<div class="myThirdOfWidth" id="id_generalInfo">');
    $("#id_generalInfo").append( '<div class="oneLine">Contrat name: ' + generalInfo.name + '</div>' );
    $("#id_generalInfo").append( '<div class="oneLine">Contrat expiry: ' + generalInfo.expiry + '</div>' );
    var ltHelpStr = "La derniere personne qui ach&egrave;te ou vend un contrat recup&egrave;re le 'liquidity token'. Celui qui d&eacute;tient le liquidity token est ";
    ltHelpStr += "forc&eacute; de faire une offre de vente et une offre d'achat dont la diff&eacute;rence de prix est de 10 chochoros. Cela signifie que si vous achetez ";
    ltHelpStr += "(respectivement vendez) un contrat, le syst&egrave;me vous force &agrave; devoir en acheter (respectivement vendre) un second ";
    ltHelpStr += "au m&ecirc;me prix moins un chochoro (respectivement plus un chochoro) ou &agrave; deboucler la transaction en vous faisant 10 chochoros de gain.";
        
    ltHelpStr = helpStr1+ltHelpStr+helpStr2;
    $("#id_generalInfo").append( '<div class="oneLine">Contrat liquidity token holder ' +ltHelpStr+': ' + generalInfo.liquidityTokenHolder + '</div>' );
    $("#id_generalInfo").append( '<div class="oneLine">Contrat last trade date: ' + generalInfo.lastTradeDate + '</div>' );
    $("#id_generalInfo").append( '<div class="oneLine">Contrat last trade price: ' + generalInfo.lastTradePrice + '</div>' );
    $("#id_generalInfo").append( '<div class="oneLine">Total number of exchanged contracts: ' + generalInfo.numberOfExchangedContracts + '</div>' );
    $("#id_generalInfo").append( '<div class="oneLine">Number of contracts sold by me : ' + generalInfo.numberOfSoldContracts + '</div>' );
    $("#id_generalInfo").append( '<div class="oneLine">My average buying price : ' + generalInfo.averageBuyingPrice + '</div>' );
    $("#id_generalInfo").append( '<div class="oneLine">Number of contracts bought by me : ' + generalInfo.numberOfBoughtContracts + '</div>' );
    $("#id_generalInfo").append( '<div class="oneLine">My average selling price : ' + generalInfo.averageSellingPrice + '</div>' );
    if( generalInfo.settlementStatus < 0 ) {
        $("#id_generalInfo").append( '<div class="oneLine">Expected P&L : ' + generalInfo.expectedPAndL + '</div>' );
        $("#id_generalInfo").append( '<div class="oneLine">Best case P&L : ' + generalInfo.bestCasePAndL + '</div>' );
        $("#id_generalInfo").append( '<div class="oneLine">Worst case P&L : ' + generalInfo.worstCasePAndL + '</div>' );
    }
    else {
        $("#id_generalInfo").append( '<div class="oneLine">Realised case P&L : ' + generalInfo.realisedPandL + '</div>' );
    }
	// trades history
	var nTrades = contractInfo.tradePricesHisto.length
    if( nTrades > 0 )
	{
	    //- otherwise display on the right (2 thirds)
	    $("#id_infoAndGraphBlock").append('<div class="myTwoThirdsOfWidth" id="id_graphBlock"></div>');
	    $("#id_graphBlock").append('<div id="pricechart_div">');
	    tradePricesHisto = contractInfo.tradePricesHisto[0];
	    var pricesData = new google.visualization.DataTable();
	    pricesData.addColumn('string', 'time');
	    pricesData.addColumn('number', 'price');
	    pricesData.addRows(nTrades);
        for( var trade = 0; trade < nTrades; trade++ )
        {
            pricesData.setValue( trade, 0, contractInfo.tradePricesHisto[trade].tradeDate );
            pricesData.setValue( trade, 1, contractInfo.tradePricesHisto[trade].tradePrice );
        }

        var pricechart = new google.visualization.LineChart(document.getElementById('pricechart_div'));
	    pricechart.draw(pricesData, 
	        {
	            width: 600,
	            height: 300,
	            title: 'Traded prices History',
	            lineWidth:1,
	            pointSize:1,
	            curveType:'function',
	            hAxis:{ textStyle:{color: 'black', fontName: 'arial', fontSize: 3, textPosition:'in'} },
	            vAxis:{ textStyle:{color: 'black', fontName: 'arial', fontSize: 3} }
	        });
	}
}

//--------------------------------------------------------------------------------------------------------------------
// sell to the highest bid
function hitBid()
{
   return submitWithoutReload( 
    '/hitBid/',
    $('#id_otherbid'),
    '#id_messageDivHitBid',
    '',
    function(){
                $('#id_messageDivHitBid').text( 'Contract successfull sold' );
                setTimeout( function() { $('#id_messageDivHitBid').fadeOut(); }, 3000 );
                return false; 
             }
    );
}
//--------------------------------------------------------------------------------------------------------------------
// buy to the lowest bid
function liftOffer()
{
   return submitWithoutReload( 
    '/liftOffer/',
    $('#id_otheroffer'),
    '#id_messageDivLiftOffer',
    '',
    function(){
                $('#id_messageDivLiftOffer').text( 'Contract successfull bought.' );
                setTimeout( function() { $('#id_messageDivLiftOffer').fadeOut(); }, 3000 );
                return false; 
             }
    );
}

//--------------------------------------------------------------------------------------------------------------------
// add a new bid
function addABid()
{
   return submitWithoutReload( 
    '/addABid/',
    $('#id_mybid'),
    '#id_messageDivAddBid',
    '',
    function(){
                $('#id_messageDivAddBid').text( 'Bid successfull added to the order book.' );
                setTimeout( function() { $('#id_messageDivAddBid').fadeOut(); }, 3000 );
                return false; 
             }
    );
}

//--------------------------------------------------------------------------------------------------------------------
// add a new offer
function addAnOffer()
{
   return submitWithoutReload( 
    '/addAnOffer/',
    $('#id_myoffer'),
    '#id_messageDivAddOffer',
    '',
    function(){
                $('#id_messageDivAddOffer').text( 'Offer successfull added to the order book.' );
                setTimeout( function() { $('#id_messageDivAddOffer').fadeOut(); }, 3000 );
                return false; 
             }
    );
}

//--------------------------------------------------------------------------------------------------------------------
// specify the number of bids
function specifyNumberOfBids( bidIndex )
{
   return submitWithoutReload( 
    '/specifyNumberOfBids/',
    $('#id_specifyNumberOfBids'+bidIndex),
    '#id_messageDivAddBid',
    '',
     function(){
                $('#id_messageDivAddBid').text( 'Your number of bid has been succesfully adjusted.' );
                setTimeout( function() { $('#id_messageDivAddBid').fadeOut(); }, 3000 );
                return false; 
             }
    );
}

//--------------------------------------------------------------------------------------------------------------------
// specify the number of offers
function specifyNumberOfOffers( offerIndex )
{
   return submitWithoutReload( 
    '/specifyNumberOfOffers/',
    $('#id_specifyNumberOfOffers'+offerIndex),
    '#id_messageDivAddOffer',
    '',
    function(){
                $('#id_messageDivAddOffer').text( 'Your number of bid has been succesfully adjusted.' );
                setTimeout( function() { $('#id_messageDivAddOffer').fadeOut(); }, 3000 );
                return false; 
             }
    );
}

